import { View, Text, Map, Button } from "@tarojs/components";
import { useState, useEffect } from "react";
import Taro, { useDidShow } from "@tarojs/taro";
import { btq } from "../../utils/to";

import {
  AtButton,
  AtModal,
  AtModalHeader,
  AtModalContent,
  AtModalAction,
  AtInput,
  AtList,
  AtListItem,
  AtSwipeAction,
  AtFloatLayout,
  AtMessage,
  AtActionSheet,
  AtActionSheetItem,
  AtPagination
} from "taro-ui";

import "./index.scss";

import { baseUrl } from "../../utils/http";

import {
  getProjectListApi,
  removeProjectApi,
  getProjectChangeApi,
  getAreaApi
} from "../../utils/api";

import { useSelector, useDispatch } from "react-redux";

const Project = () => {
  const [lon, setlon] = useState("");
  const [lat, setlat] = useState("");
  // 工程列表数据
  const [data, setData] = useState([]);
  // 地图marker
  const [markers, setmarkers] = useState([]);
  // 是否打开详情弹框
  const [modalOpen, setModalOpen] = useState(false);
  const [actionOpen, setActionOpen] = useState(false);
  const [prodectinfo, setProdectinfo] = useState({});

  // 过滤狂
  const [filterOpen, set_filterOpen] = useState(false);
  const [filterValue, set_filterValue] = useState("");
  const [filtering, set_filtering] = useState(false);

  // 第几页
  const [currentPage, setCurrentPage] = useState(1);
  // 每页条数
  const [pageSize, setPageSize] = useState(10);
  // 总数
  const [total, setTotal] = useState(0);

  const [atMessage, setAtMessage] = useState(false);

  const satellite = useSelector(state => state.yq.satellite);
  const dispatch = useDispatch();

  // 分页切换
  const pageChange = e => {
    setCurrentPage(e.current);
  };

  useEffect(() => {
    getList();
  }, [currentPage]);

  const actionClose = () => {
    setActionOpen(false);
  };

  const open = item => {
    setProdectinfo(item);
    setActionOpen(true);
  };

  useDidShow(() => {
    getList();
    getAreaApi({
      code: Taro.getStorageSync("code")
    }).then(res => {
      const arr = btq(+res.record.lng, +res.record.lat);
      setlon(+arr[0]);
      setlat(+arr[1]);
    });
    setAtMessage(true);
  });

  // 获取工程信息
  const getList = async keyword => {
    const res = await getProjectListApi({
      get_count: pageSize,
      start_index: pageSize * (currentPage - 1),
      proj_keyword: keyword || ""
    });
    if (res.res === 0) {
      setTotal(res.total_count);
      const records = res.records;
      setData(records);
      const mks = records.map(item => {
        const arr = btq(item.longitude / 1000000, item.latitude / 1000000);
        if (item.termite_wait_count > 0) {
          return {
            latitude: arr[1],
            longitude: arr[0],
            title: item.name,
            iconPath: baseUrl + "/static/icon_red.png",
            width: 40,
            height: 60
          };
        } else {
          if (item.termite_count > 0) {
            return {
              latitude: arr[1],
              longitude: arr[0],
              title: item.name,
              iconPath: baseUrl + "/static/icon_yellow.png",
              width: 40,
              height: 60
            };
          } else {
            return {
              latitude: arr[1],
              longitude: arr[0],
              title: item.name,
              iconPath: baseUrl + "/static/icon_green.png",
              width: 40,
              height: 60
            };
          }
        }
      });
      if (keyword) {
        set_filtering(true);
        Taro.setNavigationBarTitle({
          title: "过滤中(" + keyword + ")..."
        });
      } else {
        set_filtering(false);
        Taro.setNavigationBarTitle({
          title: "工程列表"
        });
      }
      set_filterValue("");
      set_filterOpen(false);
      setmarkers(mks);
    } else {
      Taro.atMessage({
        message: res.msg,
        type: "warning"
      });
    }
  };

  // 跳转到工程信息页
  const gotoDetail = () => {
    setActionOpen(false);
    dispatch({ type: "changeScale", scale: 0 });
    dispatch({ type: "changeMap", lon: 0, lat: 0 });
    Taro.navigateTo({
      url: "/pages/packagea/project_info/index?id=" + prodectinfo.project_id
    });
  };

  const gotoChange = () => {
    setActionOpen(false);
    Taro.navigateTo({
      url: "/pages/packagea/project_change/index?id=" + prodectinfo.project_id
    });
  };

  // 跳转到布点页面
  const gotoPoint = () => {
    if (prodectinfo.longitude) {
      setActionOpen(false);
      setAtMessage(false);
      Taro.navigateTo({
        url:
          "/pages/packagec/point/index?longitude=" +
          prodectinfo.longitude +
          "&latitude=" +
          prodectinfo.latitude +
          "&id=" +
          prodectinfo.project_id
      });
    } else {
      Taro.atMessage({
        message: "请先设置工程的经纬度",
        type: "warning"
      });
    }
  };

  // 打开删除model
  const removeItem = () => {
    setActionOpen(false);
    setModalOpen(true);
  };

  // 关闭删除modal
  const closeModal = () => {
    setModalOpen(false);
  };

  const confirmModal = async () => {
    const res = await removeProjectApi({
      project_id: prodectinfo.project_id
    });
    if (res.res === 0) {
      Taro.atMessage({
        message: "删除成功",
        type: "success"
      });
      setModalOpen(false);
      getList();
    }
  };

  const goToAdd = () => {
    Taro.navigateTo({
      url: "/pages/packagea/project_add/index"
    });
  };

  const gotoProjectUser = () => {
    Taro.navigateTo({
      url: "/pages/packagea/project_user/index?id=" + prodectinfo.project_id
    });
  };

  // const changeState = async state => {
  //   const res = await getProjectChangeApi({
  //     project_id: prodectinfo.project_id,
  //     state
  //   });
  //   if (res.res === 0) {
  //     setActionOpen(false);
  //     Taro.atMessage({
  //       message: "状态变更成功",
  //       type: "success"
  //     });
  //     getList();
  //   }
  // };

  // 过滤
  const openFilter = () => {
    if (!filtering) {
      set_filterOpen(true);
    } else {
      getList();
    }
  };

  const cancelFilter = () => {
    set_filterOpen(false);
  };

  const closeFilter = () => {
    set_filterOpen(false);
  };

  const confirmFilter = () => {
    set_filterOpen(false);
    getList(filterValue);
  };

  const filterChange = value => {
    set_filterValue(value);
  };

  const changeSatellite = () => {
    dispatch({ type: "changeSatellite" });
  };

  return (
    <View className="index">
      <Map
        longitude={lon}
        latitude={lat}
        style={{ width: "100%", height: 300 }}
        scale={10}
        markers={markers}
        enable-satellite={satellite}
      ></Map>
      <View className="button-wrap">
        <View className="button-item" onClick={openFilter}>
          {filtering ? "取消过滤" : "工程过滤"}
        </View>
        <View className="button-item" onClick={goToAdd}>
          新建工程
        </View>
        <View className="button-item" onClick={changeSatellite}>
          {satellite ? "切换标准地图" : "切换卫星地图"}
        </View>
      </View>
      <View className="at-article__h2">工程列表</View>
      <AtList>
        {data.map(item => {
          return (
            <AtListItem
              title={item.name}
              arrow="right"
              onClick={() => open(item)}
            />
          );
        })}
      </AtList>

      {data.length && (
        <AtPagination
          total={total}
          pageSize={pageSize}
          current={currentPage}
          onPageChange={pageChange}
        />
      )}

      {/* 过滤弹框 */}
      {filterOpen && (
        <AtModal isOpened={filterOpen} onClose={closeFilter}>
          <AtModalHeader>工程筛选</AtModalHeader>
          <AtModalContent>
            <AtInput
              name="value"
              title="关键字"
              type="text"
              value={filterValue}
              onChange={filterChange}
            />
          </AtModalContent>
          <AtModalAction>
            {" "}
            <Button onClick={cancelFilter}>取消</Button>{" "}
            <Button onClick={confirmFilter}>确定</Button>{" "}
          </AtModalAction>
        </AtModal>
      )}

      {/* 删除确认 */}
      <AtModal isOpened={modalOpen} closeOnClickOverlay={false}>
        <AtModalContent>
          您确定要删除{prodectinfo.name}这个工程吗?
        </AtModalContent>
        <AtModalAction>
          {" "}
          <Button onClick={closeModal}>取消</Button>{" "}
          <Button onClick={confirmModal}>确定</Button>{" "}
        </AtModalAction>
      </AtModal>
      {atMessage && <AtMessage />}

      {/* 动作面板 */}
      <AtActionSheet
        isOpened={actionOpen}
        cancelText="取消"
        onClose={actionClose}
        onCancel={actionClose}
      >
        {/* {prodectinfo.state === 1 ? (
          <AtActionSheetItem onClick={() => changeState(2)}>
            启用工程
          </AtActionSheetItem>
        ) : (
          <AtActionSheetItem onClick={() => changeState(1)}>
            停用工程
          </AtActionSheetItem>
        )} */}

        <AtActionSheetItem onClick={gotoDetail}>查看工程详情</AtActionSheetItem>
        <AtActionSheetItem onClick={gotoChange}>修改工程信息</AtActionSheetItem>
        <AtActionSheetItem onClick={gotoPoint}>查看布点</AtActionSheetItem>
        <AtActionSheetItem onClick={gotoProjectUser}>
          工程用户列表
        </AtActionSheetItem>
        {/* <AtActionSheetItem onClick={gotoLonlat}>修改经纬度</AtActionSheetItem> */}
        <AtActionSheetItem onClick={removeItem}>删除工程</AtActionSheetItem>
      </AtActionSheet>
    </View>
  );
};

export default Project;
